<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;

/*音频资源章节管理model*/

class ResourceAudioChapterInfo extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_audio_chapter_info';


    /**
     * 获取视频资源章节列表
     * @param keywords 检索条件
     * @param audio_id 音频资源id
     * @param page int 当前页
     * @param limit int 分页大小
     */
    public function lists($search_data = [])
    {
        $audio_id = $search_data['audio_id'] ?? '';
        $keywords = $search_data['keywords'] ?? '';
        $limit = !empty($search_data['limit']) ? $search_data['limit'] : 10;

        if (empty($field)) {
            $field = ['id', 'audio_id', 'chapter_name', 'chapter_src', 'sort', 'size', 'path', 'postfix', 'create_time'];
        }
        $res = $this->select($field)
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->Orwhere('chapter_name', 'like', "%$keywords%");
                }
            })->where(function ($query) use ($audio_id) {
                if ($audio_id) {
                    $query->where('audio_id', $audio_id);
                }
            })
            ->where('is_del', 1)
            ->orderBy('sort')
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();

        return $res;
    }

    /**
     * 获取音频章节详情
     * @param id 章节id
     */
    public function detail($id)
    {
        $field = ['id', 'audio_id', 'chapter_name', 'chapter_src', 'sort', 'size', 'path', 'postfix', 'create_time'];
        $res = $this->select($field)
            ->where('id', $id)
            ->where('is_del', 1)
            ->first();

        return $res;
    }

    /**
     * 添加章节信息
     * @param $data
     */
    public function addResource($data)
    {
        $this->add([
            'audio_id' => $data['audio_id'],
            'chapter_name' => $data['chapter_name'],
            'chapter_src' => $data['chapter_src'],
            'sort' => $data['sort'] ?? 1,
            'pid' => 0,
            'path' => 0,
            'level' => 1,
            'size' => $data['size'],
            'postfix' => $data['postfix'],
        ]);
        return true;
    }
    /**
     * 修改资源
     */
    public function changeResource($data)
    {
        return $this->where('id', $data['chapter_id'])->update([
            'chapter_name' => $data['chapter_name'],
            'chapter_src' => $data['chapter_src'],
            'sort' => $data['sort'] ?? 1,
            'pid' => 0,
            'path' => 0,
            'level' => 1,
            'size' => $data['size'],
            'postfix' => $data['postfix'],
        ]);
    }
}
